package com.k7.mobile.platform.dao.impl;

import java.sql.SQLException;
import java.util.ArrayList;
import java.util.List;

import org.apache.commons.lang.StringUtils;
import org.apache.log4j.Logger;
import org.springframework.orm.ibatis.SqlMapClientCallback;
import org.springframework.orm.ibatis.support.SqlMapClientDaoSupport;

import com.ibatis.sqlmap.client.SqlMapExecutor;
import com.k7.mobile.platform.dataobject.PageDO;

public abstract class BaseDAOImpl extends SqlMapClientDaoSupport {
	protected Logger log = Logger.getLogger(this.getClass());

	public List executeQueryForList(String selStmName, String cntStmName, PageDO query) {
		List result = null;
		if (StringUtils.isEmpty(selStmName) || StringUtils.isEmpty(cntStmName) || (query == null)) {
			return null;
		}
		if(query.getNeedPaged() == 0) return getSqlMapClientTemplate().queryForList(selStmName, query);
		Integer countNumber = (Integer) getSqlMapClientTemplate().queryForObject(cntStmName, query);

		if (countNumber != null) {
			query.setTotalItem(countNumber.intValue());
			query.validatePageInfo();
			result = getSqlMapClientTemplate().queryForList(selStmName, query);
		}

		return result == null?new ArrayList():result;
	}

	private Integer executeInsBatch(final String sqlID, final List stList) {
		Integer result = null;
		if ((sqlID != null) && (stList != null) && !stList.isEmpty()) {
			result = (Integer) getSqlMapClientTemplate().execute(
				new SqlMapClientCallback() {
					public Object doInSqlMapClient(SqlMapExecutor executor)	throws SQLException {
						executor.startBatch();
						for (int i = 0; i < stList.size(); i++) {
							executor.insert(sqlID, stList.get(i));
						}
						int n = executor.executeBatch();
						return 1;
					}
				});
		}
		return result;
	}

	public Integer executeInsertBatch(final String sqlID, final List stList) {
		return executeInsBatch(sqlID, stList);
	}
	
	private Integer executeDelBatch(final String sqlID, final List stList) {
		Integer result = null;
		if ((sqlID != null) && (stList != null) && !stList.isEmpty()) {
			result = (Integer) getSqlMapClientTemplate().execute(
				new SqlMapClientCallback() {
					public Object doInSqlMapClient(SqlMapExecutor executor)	throws SQLException {
						executor.startBatch();
						for (int i = 0; i < stList.size(); i++) {
							executor.delete(sqlID, stList.get(i));
						}
						int n = executor.executeBatch();
						return 1;
					}
				});
		}
		return result;
	}
	
	public Integer executeDeleteBatch(final String sqlID, final List stList) {
		return executeDelBatch(sqlID, stList);
	}	
}
